#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Flight策略状态监控脚本
实时监控Flight策略系统的运行状态
"""

import os
import json
import time
from datetime import datetime
from dotenv import load_dotenv
import requests

load_dotenv()

def check_flight_system_status():
    """检查Flight策略系统状态"""
    print("🎬 Flight策略系统状态监控")
    print(f"检查时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 60)
    
    # 检查配置文件
    print("\n📋 配置文件检查:")
    try:
        with open('accounts_config.json', 'r', encoding='utf-8') as f:
            config = json.load(f)
        
        flight_accounts = []
        for account_id, account_config in config['accounts'].items():
            if account_config.get('strategy') == 'flight' and account_config.get('enabled', False):
                flight_accounts.append(account_id)
        
        print(f"✅ 配置文件加载成功")
        print(f"📊 启用的Flight策略账户: {len(flight_accounts)}")
        for account in flight_accounts:
            print(f"   - {account}")
            
    except Exception as e:
        print(f"❌ 配置文件检查失败: {e}")
        return False
    
    # 检查环境变量
    print("\n🔧 环境变量检查:")
    required_vars = {
        'OKX_DEMO_API_KEY': os.getenv('OKX_DEMO_API_KEY'),
        'OKX_DEMO_SECRET': os.getenv('OKX_DEMO_SECRET'),
        'OKX_DEMO_PASSWORD': os.getenv('OKX_DEMO_PASSWORD'),
        'DEEPSEEK_API_KEY': os.getenv('DEEPSEEK_API_KEY'),
        'TELEGRAM_BOT_TOKEN': os.getenv('TELEGRAM_BOT_TOKEN'),
        'TELEGRAM_CHAT_ID': os.getenv('TELEGRAM_CHAT_ID')
    }
    
    missing_vars = []
    for var, value in required_vars.items():
        if value:
            print(f"✅ {var}: {value[:10]}...")
        else:
            print(f"❌ {var}: 未设置")
            missing_vars.append(var)
    
    if missing_vars:
        print(f"⚠️ 缺少 {len(missing_vars)} 个环境变量")
    else:
        print("✅ 所有环境变量已设置")
    
    # 检查Flight策略模块
    print("\n🧠 Flight策略模块检查:")
    try:
        import flight_strategy
        print("✅ Flight策略模块导入成功")
        
        # 检查关键函数
        required_functions = [
            'analyze_with_flight',
            'get_flight_ohlcv_data', 
            'init_flight_exchange',
            'FLIGHT_CONFIG'
        ]
        
        for func_name in required_functions:
            if hasattr(flight_strategy, func_name):
                print(f"✅ {func_name}")
            else:
                print(f"❌ {func_name} 不存在")
                
    except ImportError as e:
        print(f"❌ Flight策略模块导入失败: {e}")
        return False
    
    # 检查多账号管理器
    print("\n👥 多账号管理器检查:")
    try:
        import multi_account_manager
        print("✅ 多账号管理器导入成功")
    except ImportError as e:
        print(f"❌ 多账号管理器导入失败: {e}")
        return False
    
    # 检查日志文件
    print("\n📝 日志文件检查:")
    import glob
    log_files = glob.glob('logs/*flight*.log')
    if log_files:
        print(f"✅ 找到 {len(log_files)} 个Flight策略日志文件:")
        for log_file in log_files:
            try:
                with open(log_file, 'r', encoding='utf-8') as f:
                    lines = f.readlines()
                    print(f"   - {log_file}: {len(lines)} 行")
            except Exception as e:
                print(f"   - {log_file}: 读取失败 ({e})")
    else:
        print("⚠️ 未找到Flight策略日志文件")
    
    # 检查网络连接
    print("\n🌐 网络连接检查:")
    try:
        # 测试DeepSeek API
        response = requests.get("https://api.deepseek.com", timeout=5)
        print("✅ DeepSeek API连接正常")
    except Exception as e:
        print(f"❌ DeepSeek API连接失败: {e}")
    
    try:
        # 测试Telegram API
        bot_token = os.getenv('TELEGRAM_BOT_TOKEN')
        if bot_token:
            response = requests.get(f"https://api.telegram.org/bot{bot_token}/getMe", timeout=5)
            if response.status_code == 200:
                print("✅ Telegram Bot连接正常")
            else:
                print(f"❌ Telegram Bot连接失败: {response.status_code}")
        else:
            print("❌ Telegram Bot Token未设置")
    except Exception as e:
        print(f"❌ Telegram Bot连接失败: {e}")
    
    # 检查进程状态
    print("\n🔄 进程状态检查:")
    try:
        import subprocess
        result = subprocess.run(['pgrep', '-f', 'multi_account_manager.py'], 
                              capture_output=True, text=True)
        if result.returncode == 0:
            pids = result.stdout.strip().split('\n')
            print(f"✅ 找到 {len(pids)} 个多账号管理器进程: {pids}")
        else:
            print("⚠️ 未找到运行中的多账号管理器进程")
    except Exception as e:
        print(f"❌ 进程检查失败: {e}")
    
    print(f"\n🎯 状态检查完成 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print("=" * 60)
    
    return len(missing_vars) == 0

def show_flight_config():
    """显示Flight策略配置"""
    print("\n⚙️ Flight策略配置详情")
    print("=" * 60)
    
    try:
        import flight_strategy
        config = flight_strategy.FLIGHT_CONFIG
        
        print(f"📊 基础配置:")
        print(f"   杠杆倍数: {config['leverage']}x")
        print(f"   时间周期: {config['timeframe']}")
        print(f"   仓位比例: {config['position_size_ratio']*100:.1f}%")
        print(f"   每日限额: {config['daily_trade_limit']}次")
        print(f"   最大持仓: {config['max_concurrent_positions']}个")
        
        print(f"\n🛡️ 风险管理:")
        print(f"   止损比例: {config['stop_loss_ratio']*100:.1f}%")
        print(f"   止盈比例: {config['take_profit_ratio']*100:.1f}%")
        print(f"   盈亏比: 1:{config['take_profit_ratio']/config['stop_loss_ratio']:.1f}")
        
        print(f"\n📈 交易参数:")
        print(f"   天量阈值: {config['volume_spike_threshold']}x")
        print(f"   关键位容差: {config['key_level_tolerance']*100:.1f}%")
        print(f"   逆势风险系数: {config['contrarian_risk_multiplier']}")
        print(f"   背离周期: {config['divergence_periods']}")
        print(f"   最小背离点: {config['min_divergence_points']}")
        
        print(f"\n💎 交易对:")
        for symbol_config in config['symbols']:
            print(f"   {symbol_config['symbol']}: {symbol_config['amount']}")
        
        print(f"\n📱 通知设置:")
        print(f"   Telegram启用: {config['telegram_enabled']}")
        print(f"   Bot Token: {'已设置' if config['telegram_bot_token'] else '未设置'}")
        print(f"   Chat ID: {'已设置' if config['telegram_chat_id'] else '未设置'}")
        
    except Exception as e:
        print(f"❌ 配置显示失败: {e}")

def main():
    """主函数"""
    import sys
    
    if len(sys.argv) > 1:
        command = sys.argv[1]
        
        if command == "config":
            show_flight_config()
        elif command == "status":
            check_flight_system_status()
        else:
            print(f"❌ 未知命令: {command}")
            print(f"可用命令: status, config")
    else:
        # 默认执行状态检查
        if check_flight_system_status():
            show_flight_config()
            
            print(f"\n🚀 启动建议:")
            print(f"   如果系统未运行，请执行:")
            print(f"   python multi_account_manager.py")
            print(f"\n📊 监控建议:")
            print(f"   python flight_status_monitor.py status")
            print(f"\n📝 查看日志:")
            print(f"   tail -f logs/demo_flight_trading.log")

if __name__ == "__main__":
    main()
